import { useQuery } from "@tanstack/react-query"
import type { Options } from "ky"
import ky, { HTTPError } from "ky"


const kyInstance = ky.create({
  prefixUrl: '/api',
  retry: 1,
  hooks: {
    beforeRequest: [
      (request, options) => {
        console.log('base beforeRequest')
        // request.headers.set('X-Requested-With', 'ky')
      }
    ],

  }
})

const newInstance = kyInstance.create({
  prefixUrl: '/api',
  retry: 1,
  hooks: {
    beforeRequest: [
      (request, options) => {
        console.log('new beforeRequest')
      }
    ],
  }
})

const formData = new FormData()
formData.append('name', 'lucardo3')
formData.append('age', '20')
type QueryKey = [string, Options?]
export function RequestHookTest() {

  const { data: data, isLoading: isLoading } = useQuery({
    queryKey: ['success/201', 'x-www-form-urlencoded', 'get'],
    queryFn: () => kyInstance('success/201').json()
  })
  /* const { data: data1, isLoading: isLoading1 } = useQuery({
    queryKey: ['server-error/503', 'x-www-form-urlencoded', 'get'],
    queryFn: () => kyInstance('server-error/503', {

      hooks: {
        afterResponse: [
          (_request, _options, response) => {
            // You could do something with the response, for example, logging.
            if (true) {
              throw new HTTPError(response, _request, _options)
            }

            // 或者返回个Response, 覆盖原来的响应
            return new Response('返回一个不同的响应', { status: 200 });
          },

          //  因为上一个hook 抛出了错误, 因此该hook 不会执行
          async (request, options, response) => {
            // 做点什么事情
          }
        ],
        beforeRetry: [
          // 此hook会执行
          (state) => {
            console.log('custom beforRetry', state)
            return ky.stop
          }
        ],
        beforeError: [
          // 因为在afterResponse 中抛出了错误, 因此该hook 不会执行
          (error) => {
            const { response, request, options } = error
            console.error('custom beforeError', error)
            return error
          }
        ]
      }
    }).json()
  }) */

  const { data: data2, isLoading: isLoading2 } = useQuery({
    queryKey: ['success/201', 'x-www-form-urlencoded', 'get', 'newInstance'],
    queryFn: () => newInstance('success/201').json()
  })

  return <main className="p-4">

    <h2 className="text-2xl font-bold mb-4">success/201 get 响应内容</h2>
    <pre>
      {isLoading ? 'loading...' : JSON.stringify(data, null, 2)}
    </pre>

    <h2 className="text-2xl font-bold mb-4">server-error/503 get 响应内容</h2>
    {/* <pre>
      {isLoading1 ? 'loading...' : JSON.stringify(data1, null, 2)}
    </pre> */}

    <h2 className="text-2xl font-bold mb-4">success/201 get 响应内容(newInstance)</h2>
    <pre>
      {isLoading2 ? 'loading...' : JSON.stringify(data2, null, 2)}
    </pre>



  </main>
}